<?php


namespace App\Service\College;

use App\Models\College\CollegeCourseModel;
use App\Models\Common\ResourcesModel;
use Exception;

class CoursesService
{

    const FILE_COURSES_COVER_IMG = "coursesCoverImg";//课程封面图
    const FILE_COURSES_WARE_VIDEO = "courseWareVideo";//课件视频资源
    const FILE_COURSES_WARE_PDF = "coursesWarePdf";//课件pdf
    const FILE_COURSES_WARE_IMG = "coursesWareImg";//课件图片

    /**
     * 获取课程列表
     * @param $pageSize
     * @param $pageNum
     * @param $name
     * @param $categoryId
     * @return mixed
     */
    public static function getCoursesList($pageSize, $pageNum, $name, $categoryId)
    {
        $paginator = CollegeCourseModel::query()
            ->when(
                $name, function ($query) use ($name) {
                $query->where('name', 'like', "%{$name}%");
            }
            )
            ->when(
                $categoryId, function ($query) use ($categoryId) {
                $query->where('categoryId', $categoryId);
            }
            )
            ->with('categoryRel')
            ->orderByDesc('status')
            ->orderByDesc('updatedAt')
            ->paginate(
                $pageSize, ['id', 'name', 'desc', 'type', 'categoryId', 'createdAt', 'status'],
                $pageName = 'page', $pageNum
            );


        $lists = $paginator->map(
            function (CollegeCourseModel $collegeCourseModel) {
                return [
                    'id'           => $collegeCourseModel->id,
                    'name'         => $collegeCourseModel->name,
                    'type'         => $collegeCourseModel->type,
                    'desc'         => $collegeCourseModel->campus,
                    'categoryId'   => $collegeCourseModel->categoryId,
                    'createdAt'    => $collegeCourseModel->createdAt->toDateTimeString(),
                    'status'       => $collegeCourseModel->status,
                    'categoryName' => (string)optional($collegeCourseModel->categoryRel)->name,
                ];
            }
        );

        return [
            'pageNum'   => $paginator->currentPage(),
            'pageSize'  => $paginator->perPage(),
            'pageCount' => ceil($paginator->total() / $paginator->perPage()),
            'count'     => $paginator->total(),
            'lists'     => $lists,
        ];
    }

    /**
     * 添加课程
     * @param $request
     * @throws Exception
     */
    public static function addCourses($request)
    {
        try {
            $data = [
                'name' => $request->name,
                'desc' => $request->desc,
                'type' => $request->type,
                'status' => $request->status,
                'categoryId' => $request->categoryId,
            ];
            $res = CollegeCourseModel::addCourses($data);
            //处理资源数据
            self::updateResourcesBatch($res->toArray()['id'], $request->coverImg, $request->resource);
        } catch (Exception $e) {
            handleException($e);
        }
    }

    /**
     * 处理课程上传附件入库
     * @param $id
     * @param $coverImg
     * @param $fileResource
     */
    public static function updateResourcesBatch($id, $coverImg, $fileResource)
    {
        $resources[] = [//封面图
            'resourcesName' => self::FILE_COURSES_COVER_IMG,
            'url' => ltrim(parse_url($coverImg, PHP_URL_PATH), '/'),
            'sort' => 0,
        ];
        $resource = $fileResource;//视频/附件资源
        foreach ($resource as $k => $v) {
            $name = self::FILE_COURSES_WARE_VIDEO;
            if ($v['type'] == 'pdf') {
                $name = self::FILE_COURSES_WARE_PDF;
            } elseif ($v['type'] == 'image') {
                $name = self::FILE_COURSES_WARE_IMG;
            }
            $resources[] = [
                'resourcesName' => $name,
                'url' => ltrim(parse_url($v['url'], PHP_URL_PATH), '/'),
                'type' => $v['type'],
                'duration' => $v['duration'],
                'name' => $v['name'],
                'size' => $v['size'],
                'time' => $v['time'],
                'sort' => $k,
            ];
        }
        ResourcesModel::moduleBusinessResourcesBatchUpdate(
            $resources,
            ResourcesModel::MODULE_TYPE_COLLEGE,
            ResourcesModel::BUSINESS_COLLEGE_COURSES, $id,
            [self::FILE_COURSES_COVER_IMG, self::FILE_COURSES_WARE_VIDEO, self::FILE_COURSES_WARE_PDF, self::FILE_COURSES_WARE_IMG]
        );
    }

    /**
     * 修改课程
     * @param $request
     * @throws Exception
     */
    public static function updateCourses($request)
    {
        try {
            $data = [
                'name' => $request->name,
                'desc' => $request->desc,
                'type' => $request->type,
                'status' => $request->status,
                'categoryId' => $request->categoryId,
            ];
            CollegeCourseModel::setCoursesInfoById($request->id, $data);
            //处理资源数据
            self::updateResourcesBatch($request->id, $request->coverImg, $request->resource);
        } catch (Exception $e) {
            handleException($e);
        }
    }

    /**
     * get info
     * @param $request
     * @return array
     */
    public static function getCoursesInfo($request)
    {
        $coursesInfo = CollegeCourseModel::getCoursesInfoById($request->id);
        if ($coursesInfo) {
            $coursesInfo = $coursesInfo->toArray();
            //查询课程附件资源
            $resources = ResourcesModel::getModuleBusinessBatchResources(ResourcesModel::MODULE_TYPE_COLLEGE, ResourcesModel::BUSINESS_COLLEGE_COURSES, $request->id);
            $coursesInfo['resource'] = [];
            $coursesInfo['coverImg'] = "";
            foreach ($resources as $resource) {
                $extra = [];
                if ($resource['extra']) {
                    $extra = json_decode($resource['extra'], true);
                }
                switch ($resource['name']) {
                    case self::FILE_COURSES_COVER_IMG ://课程封面图
                        $coursesInfo['coverImg'] = picturePath($resource['url']);
                        break;
                    case self::FILE_COURSES_WARE_VIDEO://课件视频资源
                    case self::FILE_COURSES_WARE_PDF ://课件pdf
                    case self::FILE_COURSES_WARE_IMG ://课件图片
                        $coursesInfo['resource'][] = [
                            'url' => picturePath($resource['url']),
                            'type' => $extra['type'] ?? "",
                            'duration' => $extra['duration'] ?? 0,
                            'name' => $extra['name'] ?? "",
                            'size' => $extra['size'] ?? 0,
                            'time' => $extra['time'] ?? "",
                        ];
                        break;
                }
            }
        }
        return $coursesInfo;
    }


    /**
     * 删除课程
     * @param $request
     * @return mixed|void
     */
    public static function deleteCourses($request)
    {
        $res = CollegeCourseModel::setCoursesInfoById($request->id, [
            'isDeleted' => 1
        ]);
        if ($res) {
            //清理课程附件资源
            ResourcesModel::query()->where("module", ResourcesModel::MODULE_TYPE_COLLEGE,)
                ->where("business", ResourcesModel::BUSINESS_COLLEGE_COURSES)
                ->where("businessId", $request->id)
                ->update(["isDeleted" => 1]);
        }
    }


}
